﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using Softyum.Common.xml;

namespace Softyum.ForexAgent.Site
{
    public class NewsSourceManager
    {
        public string DataFolder { set; get; }
        public IList<WebSiteCategory> Categories { get; set; }

        public NewsSourceManager()
        {
            Categories = new List<WebSiteCategory>();
            DataFolder = AppDomain.CurrentDomain.BaseDirectory + @"Data\";

            //
            Initialize();
        }

        private void Initialize()
        {
            LoadCategories();
            LoadSites();
        }

        private void LoadCategories()
        {
            //
            Categories.Clear();
            //
            if (Directory.Exists(DataFolder))
            {
                foreach (var item in Directory.GetDirectories(DataFolder))
                {
                    DirectoryInfo di = new DirectoryInfo(item);
                    AddCategory(di.Name);
                }
            }
        }
        
        private void LoadSites()
        {
            foreach (WebSiteCategory c in Categories)
            {
                LoadPageList(c);
            }
        }

        private void LoadPageList(WebSiteCategory c)
        {
            foreach (var filepath in Directory.GetFiles(c.Path))
            {
                FileInfo fi = new FileInfo(filepath);
                if (fi.Extension.ToLower().Equals(".xml"))
                {
                    WebPage page = new WebPage();

                    XDocument doc = XDocument.Load(filepath);
                    XElement e = doc.Element("site");
                    page.Name = e.Attribute("name").Value;
                    page.Title = XmlHelper.ReadAttrString(e, "title", page.Name);
                    page.Enabled = XmlHelper.ReadAttrBoolean(e, "enabled", true);
                    page.Url = e.Attribute("url").Value;
                    page.Encoding = XmlHelper.ReadAttrString(e, "encoding", "");
                    page.Intval = XmlHelper.ReadAttrInt(e, "intval", 60000);
                    page.BlockPattern = e.Element("block-pattern").Value;
                    page.EntryPattern = e.Element("entry-pattern").Value;
                    page.Columns.AddRange(GetColumns(doc));

                    // 
                    c.Pages.Add(page);
                }
            }
        }

        private IEnumerable<WebPage.Column> GetColumns(XDocument doc)
        {
            return from el in doc.Element("site")
                       .Element("grid")
                       .Element("columns").Elements()
                    select new WebPage.Column
                    {
                        Name = el.Attribute("name").Value,
                        Title = XmlHelper.ReadAttrString(el, "title", el.Attribute("name").Value),
                        Width = XmlHelper.ReadAttrInt(el, "width", -1),
                        Primary = XmlHelper.ReadAttrBoolean(el, "primary", false),
                        Link = XmlHelper.ReadAttrString(el, "link", ""),
                        Tooltip = XmlHelper.ReadAttrString(el, "tooltip", "")
                    };
        }


        public bool IsCategoryExist(string name)
        {
            var v = (from el in Categories
                     where (el.Name != null) && (el.Name.Equals(name))
                     select el).Count();

            return v == 1;
        }

        public int AddCategory(string name)
        {
            WebSiteCategory category = new WebSiteCategory();
            DirectoryInfo di = new DirectoryInfo(DataFolder + name);
            // create if not exists
            if (!di.Exists)
            {
                di.Create();
            }
            // 
            category.Name = di.Name;
            category.Path = di.FullName;

            // 
            Categories.Add(category);

            // 
            return Categories.Count - 1;
        }

        public void Delete(WebSiteCategory category)
        {
            Directory.Delete(category.Path, true);
            Categories.Remove(category);
        }
    }
}
